package com.zzyl.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 小程序端Token拦截器
 *
 * @Author mr.wu
 * @Date 2025-10-22 17:42
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 拦截逻辑
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是mvc的控制器资源，则放行
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 1. 获取请求头的Token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        // 2. 如果为空，则响应401
        if(StrUtil.isBlank(token)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        // 3. 解析Token
        try {
            Claims claims = tokenService.parseToken(token);

            // 5. 解析成功，放行前，获取用户ID存入ThreadLocal
            Long userId = Long.valueOf(String.valueOf(claims.get("userId")));
            UserThreadLocal.set(userId);

            // 6. 放行请求
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // 4. 解析失败，则响应401
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();//用完即删，避免出现OOM内存泄漏问题
    }
}
